﻿
Imports System.ComponentModel

Public Class frmRandomInspection
    Public IcTag As New frmStartCompleteBase.TagData
    Public LotNo As String
    Public RackNo As String
    Public ProcCD As String
    Public EquipNo As String
    Public Status As String
    '不良率判定結果
    Protected Enum DefectJudgement
        OK
        WARNING
        HOLD
        ERR
    End Enum
    Private objRCHistroy As clsRandCheckHistory
    Private dt As DataTable

    Private Sub setDataGridView()
        objRCHistroy = New clsRandCheckHistory

        'dgvList.DataSource = Nothing
        dt = Nothing
        dt = objRCHistroy.selectRandCheckHistory(LotNo, ProcCD, EquipNo, RackNo, Status)
        If IsNothing(dt) Then
            If IsNothing(dgvList.DataSource) = False Then
                Dim dt1 As DataTable = dgvList.DataSource
                dt1.Clear()
            End If
            'MsgBox(getMsgStr("MSG10048"))
        Else
            dgvList.DataSource = dt
            dgvList.Refresh()
        End If
    End Sub

    Private Sub frmRandomInspection_Load(sender As Object, e As EventArgs) Handles Me.Load

        '設備No.によって検索する
        Dim m_cIdohyo As New clsDbIdoHyo
        dgvList.AutoGenerateColumns = False
        m_cIdohyo.GetEquipInfoByID(g_CURRENT_EQUIP_ID)
        g_EQUIP_NO = m_cIdohyo.EquipInfo.szEquipNo
        If m_cIdohyo.EquipInfo.szKouteiCD1 <> "S42" Then
            txtEquipNo.Text = g_EQUIP_NO
        End If
        If m_cIdohyo.EquipInfo.szKouteiCD1 <> "" Then
            txtProcCD.Text = m_cIdohyo.EquipInfo.szKouteiCD1
        Else
            txtProcCD.Text = m_cIdohyo.EquipInfo.szKouteiCD
        End If
        btnSearch.PerformClick()

    End Sub

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click

        If isChanged() Then
            Exit Sub
        End If

        LotNo = txtLotNo.Text.Trim.ToUpper
        ProcCD = txtProcCD.Text.Trim.ToUpper
        EquipNo = txtEquipNo.Text.Trim.ToUpper
        RackNo = txtRackNo.Text.Trim.ToUpper
        Status = cmbStatus.Text.ToUpper
        setDataGridView()

    End Sub
    Private Function isChanged() As Boolean
        If IsNothing(dgvList.DataSource) Then Return False
        Dim dt As DataTable = dgvList.DataSource

        If IsNothing(dt.GetChanges) Then
            Return False
        Else
            If MsgBox(getMsgStr("MSG10055"), MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                btnComplete.PerformClick()

            End If

        End If

        Return False

    End Function
    Private Sub btnComplete_Click(sender As Object, e As EventArgs) Handles btnComplete.Click

        If IsNothing(dgvList.DataSource) Then Exit Sub
        Dim dt As DataTable = dgvList.DataSource
        If IsNothing(dt.GetChanges) Then Exit Sub
        Dim changeFlg As Boolean = False
        For Each dr As DataRow In dt.GetChanges.Rows
            If dr.RowState = DataRowState.Modified Then

                If dr("Status") = OK Then
                    If dr("ProcCD") <> "S41" AndAlso dr("ProcCD") <> "S42" AndAlso MsgBox(getMsgStr("MSG10056"), MsgBoxStyle.YesNo) = MsgBoxResult.Yes = True Then
                        CompleteLot(dr("ProcCD"), dr("LotNo"), IIf(IsDBNull(dr("userNo")), "", dr("userNO")), dr("invnum"), dr("Status"), dr("EquipNo"))
                    End If
                ElseIf dr("Status") = NG Then
                    MsgBox(getMsgStr("MSG10057"))
                End If
                objRCHistroy.updateStatus(dr("LotNo"), dr("ProcCD"), dr("RackNo"), dr("NGNum"), dr("Status"), IIf(IsDBNull(dr("CheckOpe")), "", dr("CheckOpe")))
                changeFlg = True
            End If
        Next
        If changeFlg = True Then
            MsgBox(getMsgStr("MSG00019", "数据库"))
            dt.AcceptChanges()
            'List更新
            btnSearch.PerformClick()
        End If
    End Sub


    'bsiteへ計上
    Private Sub CompleteLot(procCD As String, lotno As String, userNo As String, invnum As Integer, status As String, EquipNo As String)

        Dim inputBsite As New InSiteWebService.InMoveIn
        Dim outputBsite As New InSiteWebService.OutMoveIn
        Dim objEquipMat As New clsDbEquipMat
        Dim clientProcCd As String = ""
        Dim tmpProcessCD As String = ""
        Dim outHeader As InSiteWebService.OutHeader  ' bSite応答
        Dim outLotInfo As InSiteWebService.LotStdType ' bSite応答

        If procCD = "S41" Then
            tmpProcessCD = "A41"
            'EquipNo = "999-2-A41"
        End If
        If procCD = "S51" Then
            tmpProcessCD = "A51"
            'EquipNo = "999-2-A51"
        End If
        clientProcCd = objEquipMat.GetBsiteClientString(tmpProcessCD)
#Region "del"
        'inputBsite.Employee = userNo  '開始作業者
        'inputBsite.Lot = lotno                  'ロットNo
        'inputBsite.Machine = EquipNo         '装置No
        'inputBsite.IgnoreLimitTime = True   '強制着工

        'outputBsite = MoveInService_Execute(inputBsite, clientProcCd)
        ''戻り情報を保持
        'outHeader = outputBsite.Header
        'outLotInfo = outputBsite.LotInf
        ''A工程の着工履歴作成
        'objEquipMat.saveAProcResultForRC(procCD, tmpProcessCD, "1", lotno)

#End Region

        '----------- A工程完工 BEGIN  ----------- 
        Dim inputBsiteStd As New InSiteWebService.InMoveStd
        Dim outputBsiteStd As New InSiteWebService.OutMoveStd
        'b-Site送信用不良数
        Dim lossInf() As InSiteWebService.LossData = {}
        Dim LossQtySum As Integer = 0 'ADD 苗 2018/2/3

        Dim m_cLotBadData As New clsDBLotBadData
        Dim m_cLotDefect As New clsDbLotDefect

        Dim dtFrameNG As DataTable = Nothing
        If IsNothing(dtFrameNG) OrElse dtFrameNG.Rows.Count() = 0 Then
            dtFrameNG = getFrameNG(tmpProcessCD, lotno, EquipNo)
        End If
        If IsNothing(dtFrameNG) OrElse dtFrameNG.Rows.Count() = 0 Then
            '拡散ロットの場合は、不良数をWOKから取得する
            dtFrameNG = m_cLotBadData.GetDefectData(lotno, g_CURRENT_EQUIP_ID, tmpProcessCD)
        End If
        '<<20180113 佐川
        'ADD 苗 2018/1/18 BEGIN
        If IsNothing(dtFrameNG) OrElse dtFrameNG.Rows.Count() = 0 Then
            dtFrameNG = m_cLotDefect.GetDefectData(lotno, g_CURRENT_EQUIP_ID, tmpProcessCD)
        End If


        'ADD 苗 2018/1/18 END
        If Not (IsNothing(dtFrameNG) OrElse dtFrameNG.Rows.Count <= 0) Then
            'szCmdDefectCntSend = FixCharZero(dgvError.Rows.Count, 6)
            ReDim lossInf(dtFrameNG.Rows.Count - 1)
            For i = 1 To dtFrameNG.Rows.Count
                'szCmdDefectCntSend &= ":" & FixCharSpace(dgvError(0, i - 1).Value.ToString, 5) & ":" & FixCharSpace(dgvError(2, i - 1).Value.ToString, 6)
                'b-Site不良数セット
                lossInf(i - 1) = New InSiteWebService.LossData
                lossInf(i - 1).LossReason = dtFrameNG(0)(0).ToString
                lossInf(i - 1).LossQty = dtFrameNG(0)(dtFrameNG.Columns.Count - 1).ToString
                LossQtySum += CInt(lossInf(i - 1).LossQty) 'ADD 苗 2018/2/3
            Next
        End If

        inputBsiteStd.Employee = userNo  '終了作業者
        inputBsiteStd.Lot = lotno       'ロットNo
        inputBsiteStd.Machine = EquipNo         '装置No
        inputBsiteStd.IgnoreWarning = True    '強制着工
        inputBsiteStd.LossInf = lossInf            '不良数 TODO:CHECK

        Dim objDbCondData As New clsDbCondData
        Dim dtLot As DataTable = objDbCondData.GetWbLotData(lotno)
        Dim frameinfo As Hashtable = Nothing
        If dt.Rows.Count = 0 Then
            Exit Sub
        End If

        If dtLot(0)("FRAME_ID_USE") = "1" Then
            frameinfo = getFrameInfo(tmpProcessCD, lotno)
            If IsNothing(frameinfo) OrElse Val(frameinfo("totalPkgCnt").ToString()) = 0 Then
                MsgBox(getMsgStr("MSG10060"))
                Exit Sub
            Else
                'If Val(frameinfo("totalNgCnt").ToString()) = 0 Then
                '    inputBsiteStd.Qty = Val(frameinfo("totalPkgCnt").ToString())    '投入数
                'Else
                inputBsiteStd.Qty = Val(frameinfo("totalOkCnt").ToString())    '完成数
                'End If
                'UPD 苗 2018/2/3 END
                '>>20180302 大賀 GroupKey入力時ウェハ枚数入力

                inputBsiteStd.Qty2 = Val(frameinfo("frameCnt").ToString()) 'フレーム枚数’ADD 苗　2018/1/17

            End If
        Else
            inputBsiteStd.Qty = dtLot(0)("INVNUM") - LossQtySum   '投入数
            inputBsiteStd.Qty2 = dtLot(0)("FRAMENUM") 'フレーム枚数’ADD 苗　2018/1/17

        End If

        'inputBsiteStd.Qty = invnum - LossQtySum   '完成数

        'End If
        'UPD 苗 2018/2/3 END
        '>>20180302 大賀 GroupKey入力時ウェハ枚数入力
        'If wf_write_flag = WRITE_WAFER Then
        '    inputBsiteStd.Qty2 = IcTag.waferNum
        'Else
        'inputBsiteStd.Qty2 = IcTag.iFrame 'フレーム枚数’ADD 苗　2018/1/17
        'End If
        '<<20180302 大賀 GroupKey入力時ウェハ枚数入力
        'If Not String.IsNullOrEmpty(outWeekCode) Then
        '    inputBsite.WeeklyCode = outWeekCode '週コード
        'End If

        outputBsiteStd = MoveStdService_Execute(inputBsiteStd, clientProcCd)
        '戻り情報を保持
        outHeader = outputBsiteStd.Header
        outLotInfo = outputBsiteStd.LotInf
        If outHeader.Status = STS_SUCCESS Then

            'A工程の完工履歴作成
            objEquipMat.saveAProcResultForRC(procCD, tmpProcessCD, "3", lotno, frameinfo)

            SyncLotInfo(tmpProcessCD, lotno)
        ElseIf outHeader.Status = STS_ERROR Then
            Dim a = "(计上数量 ： " & inputBsiteStd.Lot.ToString & " : " & inputBsiteStd.Qty.ToString & ")"
            MsgBox(tmpProcessCD & "工程 计上失败 ：" & outHeader.Message & a, MsgBoxStyle.Critical)

        End If

    End Sub
    Public Sub SyncLotInfo(strProcCD As String, lotNo As String)
        Dim m_cEquipMat As New clsDbEquipMat
        Dim m_cLotInfo As New clsDbLotInfo

        Dim param As InSiteWebService.InViewLot = New InSiteWebService.InViewLot()
        param.Name = lotNo
        Dim clientStr As String = m_cEquipMat.GetBsiteClientString(strProcCD)
        Dim viewLotServiceInfo As InSiteWebService.OutLotStd = mdl_ViewLotService.ViewLotServiceGet(param, clientStr)
        If Not IsNothing(viewLotServiceInfo) AndAlso STS_SUCCESS.Equals(viewLotServiceInfo.Header.Status) Then

            m_cLotInfo.SaveTagLotInfo(lotNo, viewLotServiceInfo.LotInf.Operation)
            '>>20171202 兪
        Else
            'MsgBox("组立Key No在bSite里不存在 或者 连接不上bSite,请联系相关人员。", MsgBoxStyle.Information)
            '<<20171202 兪
        End If

    End Sub
    ''' <summary>
    ''' フレーム情報を取得して返却します。
    ''' </summary>
    ''' <returns></returns>
    Protected Function getFrameInfo(ProcCD As String， lotno As String) As Hashtable
        Dim ht As Hashtable = New Hashtable
        Dim dtFrameData As New DataTable
        Dim m_cLotDefect As New clsDbLotDefect


        dtFrameData = m_cLotDefect.GetFrameInfo(ProcCD, lotno)


        'by xulei 2018/11/13 不良情報を追加
        Dim strMapData As String = dtFrameData.Rows(0).Item("map_data")
        Dim CategoryCode As New List(Of String)
        For i = 0 To strMapData.Length - 1
            If Not strMapData.Substring(i, 1).Equals("1") And Not CategoryCode.Contains(strMapData.Substring(i, 1)) Then
                CategoryCode.Add(strMapData.Substring(i, 1))
            End If
        Next

        Dim dtMapData As New DataTable

        If CategoryCode.Count > 0 Then
            Dim strCategoryCode() As String = CategoryCode.ToArray

            dtMapData = m_cLotDefect.GetErrorInfo(g_CURRENT_EQUIP_TYPE.ToString, strCategoryCode)

            dtMapData.Columns.Add("QTY")
            Dim intError As Integer
            For i = 0 To dtMapData.Rows.Count - 1
                intError = 0
                For j = 0 To strMapData.Length - 1
                    If dtMapData.Rows(i).Item("category_code").ToString.Equals((System.Text.Encoding.Default.GetBytes(strMapData.Substring(j, 1))(0)).ToString) Then
                        intError += 1
                    End If
                Next j
                dtMapData.Rows(i).Item("QTY") = intError
            Next i


        End If
        'by xulei 2018/11/13 不良情報を追加

        If dtFrameData.Rows.Count <= 0 Then
            MsgBox(getMsgStr("MSG00181", lotno))
            Return Nothing
        ElseIf dtFrameData.Rows.Count = 1 Then
            '1レコード取れるが空の場合がある
            If IsDBNull(dtFrameData.Rows(0)("totalPkgCnt")) Then
                MsgBox(getMsgStr("MSG00181", lotno))
                Return Nothing
            End If
        End If

        'by xulei 2019/4/2 良品のないフレームからはデータを取得しないため、不良の総件数は不良詳細情報から取得
        Dim intNg As Int32 = 0
        For i = 0 To dtMapData.Rows.Count - 1
            intNg += Val(dtMapData.Rows(i).Item("QTY").ToString)
        Next
        'by xulei 2019/4/2

        For Each dr In dtFrameData.Rows
            '総数
            ht.Add("totalPkgCnt", dr("totalPkgCnt"))
            '良品数
            ht.Add("totalOkCnt", dr("totalOkCnt"))
            '不良品数
            'ht.Add("totalNgCnt", dr("totalNgCnt"))
            ht.Add("totalNgCnt", intNg)
            '空チップ数
            ht.Add("totalVacantChipCnt", dr("totalEmptyCnt"))
            '空チップ枚数
            ht.Add("vacantPcbCnt", dr("totalEmptyCnt"))
            'Ｘ印数
            ht.Add("totalCrossCnt", dr("totalCrossCnt"))
            'Ｘ印枚数
            ht.Add("crossPcbCnt", dr("crossPcbCnt"))
            'フレーム数
            ht.Add("frameCnt", dr("frameCnt"))

        Next
        Return ht
    End Function

    Private Function getFrameNG(procCD As String, lotNo As String, EquipNo As String) As DataTable

        Dim ht As Hashtable = New Hashtable
        Dim dtFrameData As New DataTable
        Dim m_cLotDefect As New clsDbLotDefect

        Dim strMapData As String = m_cLotDefect.getFrameMapData(procCD, lotNo, EquipNo)
        Dim CategoryCode As New List(Of String)
        For i = 0 To strMapData.Length - 1
            If Not strMapData.Substring(i, 1).Equals("1") And Not CategoryCode.Contains(strMapData.Substring(i, 1)) Then
                CategoryCode.Add(strMapData.Substring(i, 1))
            End If
        Next

        Dim dtMapData As New DataTable

        If CategoryCode.Count > 0 Then
            Dim strCategoryCode() As String = CategoryCode.ToArray

            dtMapData = m_cLotDefect.GetErrorInfo(g_CURRENT_EQUIP_TYPE.ToString, strCategoryCode)

            dtMapData.Columns.Add("QTY")
            Dim intError As Integer
            For i = 0 To dtMapData.Rows.Count - 1
                intError = 0
                For j = 0 To strMapData.Length - 1
                    If dtMapData.Rows(i).Item("category_code").ToString.Equals((System.Text.Encoding.Default.GetBytes(strMapData.Substring(j, 1))(0)).ToString) Then
                        intError += 1
                    End If
                Next j
                dtMapData.Rows(i).Item("QTY") = intError
            Next i

        End If

        Return dtMapData
    End Function
    ''' <summary>
    ''' B-siteからの返事を表示する
    ''' </summary>
    ''' <param name="szResult">OK/NG</param>
    ''' <remarks></remarks>
    Private Function ShowBsiteResult(ByVal szResult As String, outHeader As InSiteWebService.OutHeader) As DefectJudgement
        'If m_fNeedVerif = False Then
        Dim frmResult As New frmBsiteResult("", szResult)
        frmResult.StartPosition = FormStartPosition.CenterParent
        'B-site送信対応 結果引渡し
        frmResult.outHeader = outHeader
        frmResult.htMsgMst = htMsgMst

        If szResult = WA Then
            frmResult.btnResultOK.Text = htMsgMst("MSG00142")
        End If

        Select Case frmResult.ShowDialog()
            Case Windows.Forms.DialogResult.Retry
                ShowBsiteResult = DefectJudgement.WARNING
            Case Windows.Forms.DialogResult.Abort
                ShowBsiteResult = DefectJudgement.HOLD
            Case Else
                ShowBsiteResult = DefectJudgement.OK
        End Select

    End Function

    Private Sub btnExcelOutput_Click(sender As Object, e As EventArgs) Handles btnExcelOutput.Click
        Dim saveFileName As String = ""
        Dim saveDialog As New SaveFileDialog()

        If IsNothing(dt) Then
            'MsgBox(getMsgStr("MSG10048"))
            Exit Sub
        End If

        saveDialog.DefaultExt = "xls"
        saveDialog.Filter = "Excel文件|*.xlsx"
        'saveDialog.FileName = "a"
        saveDialog.ShowDialog()
        saveFileName = saveDialog.FileName
        If (saveFileName.IndexOf(":") < 0) Then Return ' 被点了取消
        Dim xlApp As New Microsoft.Office.Interop.Excel.Application()
        If xlApp Is Nothing Then
            getMsgStr("MSG10003", "Excel")
            Return
        End If

        Dim workbooks As Microsoft.Office.Interop.Excel.Workbooks = xlApp.Workbooks
        Dim workbook As Microsoft.Office.Interop.Excel.Workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet)
        Dim worksheet As Microsoft.Office.Interop.Excel.Worksheet = workbook.Worksheets(1) '取得sheet1
        '写入标题
        'For (i as integer = 0, i < dgvList.ColumnCount i++)
        For i As Integer = 0 To dgvList.ColumnCount - 1
            worksheet.Cells(1, i + 1) = dgvList.Columns(i).HeaderText
        Next

        '写入数值
        For r As Integer = 0 To dgvList.Rows.Count - 1
            For i As Integer = 0 To dgvList.ColumnCount - 1
                worksheet.Cells(r + 2, i + 1) = dgvList.Rows(r).Cells(i).Value
            Next
            System.Windows.Forms.Application.DoEvents()
        Next
        worksheet.Columns.EntireColumn.AutoFit() '列宽自适应
        If saveFileName <> "" Then

            Try

                workbook.Saved = True
                workbook.SaveCopyAs(saveFileName)
            Catch ex As Exception
                MsgBox(getMsgStr("MSG00010", {"Excel生成", "文件可能正被打开"}))
            End Try

        End If

        xlApp.Quit()
        GC.Collect() '强行销毁
        MsgBox(getMsgStr("MSG00019", saveDialog.FileName))
    End Sub

    Private Sub dgvList_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgvList.CellEndEdit
        If IsNothing(dgvList.DataSource) Then Exit Sub
        If e.ColumnIndex = 9 Then
            If dgvList.CurrentCell.Value >= dgvList(8, e.RowIndex).Value Then
                dgvList(10, e.RowIndex).Value = NG
            Else
                dgvList(10, e.RowIndex).Value = OK

            End If
        End If
        If e.ColumnIndex = 10 Then
            If IsDBNull(dgvList(10, e.RowIndex).Value) = False AndAlso dgvList(10, e.RowIndex).Value = NG Then
                If dgvList(9, e.RowIndex).Value = 0 OrElse dgvList(9, e.RowIndex).Value = "" Then
                    MsgBox("NG时不合格数不能为0。")
                    dgvList(10, e.RowIndex).Value = ""

                End If
            End If
        End If

    End Sub

    Private Sub frmRandomInspection_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If isChanged() Then
            e.Cancel = True
        Else
            Me.Dispose()
            e.Cancel = False
        End If
    End Sub


    Private Sub dgvList_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dgvList.CellEnter
        If TypeOf dgvList.Columns(e.ColumnIndex) Is DataGridViewComboBoxColumn And e.RowIndex <> -1 Then
            SendKeys.Send("{F4}")
        End If
    End Sub

End Class